﻿using System.Collections.Generic;
using System.Linq;
using Algoritmia.Problems.Puzzles.NQueens;

namespace Demos.Problems.Nqueens
{
    public delegate void ReinaHandler(int posicion);

    class ObservableNQueensEnumerator1: NQueensEnumerator1
    {
        public event ReinaHandler ColocarReina;
        public event ReinaHandler RetirarReina;

        override protected IEnumerable<Algoritmia.DataStructures.Lists.IList<int>> Backtracking(Algoritmia.DataStructures.Lists.IList<int> state)
        {
            if (_space.IsFinal(state))
            {
                yield return state;
            }
            foreach (var decision in _space.Decisions(state))
            {
                _decisions.Add(decision);
                if (ColocarReina != null) ColocarReina(decision);
                var successor = _space.Decide(state, decision);
                foreach (var result in Backtracking(successor))
                {
                    yield return result;
                }
                if (RetirarReina != null) RetirarReina(_decisions.Last());
                _decisions.RemoveAt(_decisions.Count - 1);
            }
        }

        public IEnumerable<Algoritmia.DataStructures.Lists.IList<int>> Enumerate(NQueensStateSpace1 space)
        {
            _decisions = _createList();
            _space = space;
            var initial = space.InitialStates.First();
            if (initial != null)
                foreach (var result in Backtracking(initial))
                {
                    ColocarReina = null;
                    RetirarReina = null;
                    yield return result;
                }
        }
    }
}